/*
    menu - fontSize
*/

import $ from '../../util/dom-core.js'
import {isContentditor,getNodeToArray,isDOMList,defaultFontSizeListConfig} from '../../util/util.js'
import DropList from '../droplist.js'

// 百度的工具函数
import Range from '../../ueditor.helper/range.js'

function getRange(){
    var range = new Range(window.document);
    var sel = window.getSelection();
    if (sel && sel.rangeCount) {
        var firstRange = sel.getRangeAt(0);
        var lastRange = sel.getRangeAt(sel.rangeCount - 1);
        range.setStart(firstRange.startContainer, firstRange.startOffset)
        .setEnd(lastRange.endContainer, lastRange.endOffset);
    }
    return range
}

const getFontSizeListMenusHtml = list => {
    const array = []
    for(let i=0;i<list.length;i++){
        const dt = list[i]
        array.push({
            $elem: $(`<span style="font-size: ${ dt }px;">${ dt }px</span>`),
            value: dt
        })
    }
    return array
}

// 构造函数  段落字号
function LineFontSize(editor) {
    var _this = this;

    const sizeList = editor.customConfig.sizeList
    const list = Array.isArray(sizeList) ? sizeList : defaultFontSizeListConfig()
    const menusHtml = getFontSizeListMenusHtml(list)

    this.editor = editor;
    this.$elem = $('<div class="w-e-menu"><i class="w-e-icon-text-heigh"></i></div>');
    this.type = 'droplist';

    // 当前是否 active 状态
    this._active = false;

    // 初始化 droplist
    this.droplist = new DropList(this, {
        width: 160,
        $title: $('<p>字号</p>'),
        type: 'list', // droplist 以列表形式展示
        list: menusHtml,
        onClick: function onClick(value) {
            // 注意 this 是指向当前的 FontSize 对象
            _this._command(value);
        }
    });
}

// 原型  段落字号
LineFontSize.prototype = {
    constructor: LineFontSize,

    // 执行命令
    _command: function _command(value) {
        var editor = this.editor;
        // 使用 styleWithCSS
        if (!editor._useStyleWithCSS) {
            document.execCommand('styleWithCSS', null, true);
            editor._useStyleWithCSS = true;
        }
        // 如果无选区，忽略
        if (!editor.selection.getRange()) {
            return;
        }

        // 恢复选取
        editor.selection.restoreSelection()

        // 借助百度ueditor的工具方法，实现字体的自定义
        const range = getRange()
        // 添加span标签，设置字体大小
        range.applyInlineStyle('span', {
            style: `font-size:${ value }px`
        });
        range.select();

        // 修改菜单状态
        editor.menus.changeActive();

        // 最后，恢复选取保证光标在原来的位置闪烁
        editor.selection.saveRange();
        editor.selection.restoreSelection();

        // 触发 onchange
        editor.change && editor.change();

    }
};



export default LineFontSize
